package com.rio.dandan.util;

import java.util.Locale;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.rio.dandan.bean.Constants;

/**
 * 
 * SessionUtils.java
 * 
 * @author 宋陆
 * @version 1.0 2014年5月21日
 */
public class SessionUtils {

    /** The session provider. */
    private static HttpSession session;
    private static final ThreadLocal<Locale> localeProvider = new ThreadLocal<Locale>();
    private static final ThreadLocal<String> ipProvider = new ThreadLocal<String>();

    public static Locale getLocale() {
        return localeProvider.get();
    }

    public static String getIpAddr() {
        return ipProvider.get();
    }

    public static void setSession(HttpSession session) {
        SessionUtils.session = session;
    }
    
    public static HttpSession getSession(){
        return SessionUtils.session;
    }

    /**
     * 每次请求初始化上下文
     * 
     * @param request
     */
    public static void buildContext(ServletRequest request) {
        HttpServletRequest req = (HttpServletRequest) request;
        request.setAttribute("uploadBaseUrl", Constants.UPLOAD_BASE_URL);
        request.setAttribute("uploadTmpUrl", Constants.UPLOAD_TMP_URL);
        request.setAttribute("uploadUserUrl", Constants.UPLOAD_USER_URL);
        localeProvider.set(req.getLocale());
        ipProvider.set(getIp(req));
    }

    public static void clear() {
        localeProvider.remove();
        ipProvider.remove();
    }

    /**
     * 获取当前请求的用户的真实IP。
     * 
     * @param request
     *            一个<code>HttpServletRequest</code>对象，如JSP页面中的
     *            <code>request</code>对象。
     * @return 返回当前请求用户的真实IP值。
     */
    private static String getIp(HttpServletRequest request) {
        if (request == null)
            return StringUtils.EMPTY;
        String ip = request.getHeader("X-Real-IP");
        if (isIp(ip))
            return ip;
        else
            ip = request.getHeader("X-Forwarded-For");

        if (isIp(ip))
            return ip;
        else
            ip = request.getHeader("Proxy-Client-IP");

        if (isIp(ip))
            return ip;
        else
            ip = request.getHeader("WL-Proxy-Client-IP");

        if (isIp(ip))
            return ip;
        else
            ip = request.getHeader("HTTP_CLIENT_IP");

        if (isIp(ip))
            return ip;
        else
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");

        if (isIp(ip))
            return ip;
        else
            ip = request.getRemoteAddr();

        return ip;
    }

    private static boolean isIp(String ip) {
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            return false;
        else
            return true;
    }
}
